var httpsUrl = getApp().globalData.httpsUrl;
var globalData = getApp().globalData;
var commonUtil = require("../../../utils/commonUtil.js")
Page({

  data: {
    imgUrl: globalData.imgUrl,
    registerFlag: 0,// 0不展示授权信息 1展示
    phoneFlag: 0,//0不展示手机授权  1展示
    pageNo: 1,
    pageSize: 50,
    orderFlag:false,
    list:[],
    businessInfo:[],
    businessId:'',
    typeList:[],
    type1:"hot",//固定分类"new"：新上 ，"sale": 促销, "hot": 热卖, "recmd": 推荐
    type2:'',//商家分类
    total:'0.00',
  },
  loadData:function(){
    let code = wx.getStorageSync("businessCode");
    var that = this;
    var params = new Object();
    params.code = code;
    let openId = wx.getStorageSync("openidKey");
    console.log("param:" + JSON.stringify(params));
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/business/getBusinessInfoByCode",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("商家信息：" + JSON.stringify(res));
        if (res.result == 0) {
          let businessInfo = res.data;
          that.setData({ businessInfo: businessInfo })
          that.setData({ businessId: businessInfo.id })
          that.types();
          that.list();
        }
      }
    })
  },
  //根据固定属性分类查
  list: function () {
    var that = this;
    var params = new Object();
    params.pageNo = this.data.pageNo;
    params.pageSize = this.data.pageSize;
    params.type = this.data.type1;
    params.businessId = this.data.businessId;
    let openId = wx.getStorageSync("openidKey");
    console.log("param:" + JSON.stringify(params));
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/goods/getPopGoodsList",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("--res：" + JSON.stringify(res));
        if (res.result == 0) {
          let rows = res.data.list;
          that.setData({ list: rows })
          that.defaultCount(rows);
        }
      }
    })
  },
  //根据商家分类id查
  list2: function () {
    var that = this;
    var params = new Object();
    params.pageNo = this.data.pageNo;
    params.pageSize = this.data.pageSize;
    params.categoryId = this.data.type2;
    params.businessId = this.data.businessId;
    let openId = wx.getStorageSync("openidKey");
    console.log("param:" + JSON.stringify(params));
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/goods/getCategoryGoods",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("--res2：" + JSON.stringify(res));
        if (res.result == 0) {
          let rows = res.data.list;
          that.setData({ list: rows })
          that.defaultCount(rows);
        }
      }
    })
  },
  defaultCount:function(rows){
    if (rows != undefined && rows.length>0){
      for (let i = 0; i < rows.length; i++) {
        rows[i].count = 0;
        rows[i].reduce_price = rows[i].reduce_price.toFixed(2);
      }
    }
    this.setData({ list: rows })
  },
  type1cg:function(e){
    let id = e.currentTarget.id;
    if (id != this.data.type1){
      this.setData({ type1: id, type2:''})
      this.list();
    }
  },
  type2cg:function(e){
    let id = e.currentTarget.id;
    if (id != this.data.type2) {
      this.setData({ type2: id, type1:'' })
      this.list2();
    }
  },
  types: function () {
    var that = this;
    var params = new Object();
    params.businessId = this.data.businessId;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/goods/getGoodsCategoryList",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("分类：" + JSON.stringify(res));
        if (res.result == 0) {
          let rows = res.data;
          that.setData({ typeList: rows })
        }
      }
    })
  },
  //商品列表加号
  addGoods:function(e){
    let index = e.currentTarget.id;
    let list = this.data.list;
    list[index].count = Number(list[index].count) + 1;
    this.setData({list:list})
    console.log(JSON.stringify(list));
    this.total();
  },
  //减数量
  jianGoods:function (e) {
    let index = e.currentTarget.id;
    let list = this.data.list;
    list[index].count = Number(list[index].count) - 1;
    this.setData({ list: list })
    console.log(JSON.stringify(list));
    this.total();
  },
  //计算总金额
  total:function(){
    let total = 0.00;
    let list = this.data.list;
    if (list != undefined && list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].count > 0){
          total = total + Number(list[i].count) * Number(list[i].reduce_price);
        }
      }
    }
    this.setData({ total: total.toFixed(2)})
    if (total == '0.00') { this.setData({ orderFlag:false})}
  },
  orderFlag: function () {
    let orderFlag = !this.data.orderFlag;
    this.setData({ orderFlag: orderFlag })
  },
  gopay:function(){
    let payGoods = [];
    let list = this.data.list;
    if (list != undefined && list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].count > 0) {
          payGoods = payGoods.concat(list[i]);
        }
      }
    }
    if(payGoods.length > 0){
      wx.setStorageSync("payGoods", payGoods);
      wx.navigateTo({
        url: '../../order/submitOrder/submitOrder',
      })
    }else{
      wx.showModal({title: '提示',content: '请至少选择一个商品',})
    }
  },
  goodsInfo:function(e){
    let id = e.currentTarget.id;
    wx.setStorageSync("goodsCode", id);
    wx.navigateTo({
      url: '../goodsInfo/goodsInfo',
    })
  },
  homepage:function(){
    wx.switchTab({
      url: '../../homepage/homepage/homepage',
    })
  },
  maidan:function(){
    wx.navigateTo({
      url: '../../order/shopPay/shopPay',
    })
  },
  onLoad: function (options) {
    console.log("options:" + JSON.stringify(options));
    const scene = decodeURIComponent(options.scene);//小程序码携带参数
    if (scene != undefined && scene != 'undefined' && scene.length > 0) {
      console.log("嗨scene:" + scene);
      wx.setStorageSync("scene", scene);
      this.getOpenId();
    }else{
      this.loadData();
    }
  },
  //小程序码携带参数：用户编码，海报编码,若str[0]为0，则str[1]为商家码
  scene:function(){
    let scene = wx.getStorageSync("scene");
    let str = scene.split(",");
    if (str[0] == 0){
      console.log("扫商家码进入");
      wx.setStorageSync("businessCode", str[1]);
      this.loadData();
    }else{
      wx.setStorageSync("parentCode", str[0]);
      wx.setStorageSync("posterCode", str[1]);
      this.getbusinessCodeByPoster();
    }
  },
  //注册后，根据海报查商家code，loadData加载商家信息
  getbusinessCodeByPoster:function(){
    let that = this;
    let posterCode = wx.getStorageSync("posterCode");
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/poster/getByCode?code=" + posterCode,
      dataType: "json",
      method: "GET",
      data: '',
      success: function (res) {
        res = res.data;
        console.log("海报信息：" + JSON.stringify(res));
        if (res.result == 0) {
          let row = res.data;
          wx.setStorageSync("businessCode", row.businessCode);
          that.loadData();
          commonUtil.openXcx();
        } else {
          wx.showModal({ title: '提示', content: res.msg })
        }
      }
    })
  },
  onShow: function () {
  },
  //用户信息检验,若不存在，则授权,若已存在判断手机号
  getOpenId: function () {
    let that = this;
    wx.login({
      success: function (res) {
        wx.showLoading({ title: '请稍等...', })
        wx.request({
          header: { "content-Type": "application/x-www-form-urlencoded" },
          url: httpsUrl + "/wechat/getOpenId",
          dataType: "json",
          method: "POST",
          data: { "code": res.code, "agentCode": globalData.agentCode },
          success: function (res) {
            wx.hideLoading();
            res = res.data;
            console.log("获取openid返回:" + JSON.stringify(res));
            if (res.result == 0) {
              let data = JSON.parse(res.data);
              wx.setStorageSync("openidKey", data.openid);
              wx.setStorageSync("sessionKey", data.session_key);
              console.log("openid:" + data.openid);
              that.searchUser();
            } else {
              console.log("获取openid失败：" + res.msg);
            }
          }
        })
      }
    })
  },
  //查询用户信息
  searchUser: function () {
    let that = this;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/member/info",
      dataType: "json",
      method: "GET",
      // data: { "openId": data.openid },
      success: function (res) {
        res = res.data;
        console.log("userInfo:" + JSON.stringify(res));
        if (res.result == 0) {
          that.scene();
          var user = res.data;
          that.setData({ user: user })
          if (commonUtil.isEmpty(user.phone)) {
            that.setData({ phoneFlag: 1 })
          }
          // commonUtil.openXcx();
        } else if (res.result == 2) {
          that.setData({ registerFlag: 1 })//{"result":2,"msg":"用户未注册!","data":null}
        }
      }
    })
  },
  //授权信息
  getUserInfo: function (e) {
    var that = this;
    //会弹框询问是否授权，拒绝则得到undefined
    //console.log("wxinfo:" + JSON.stringify(e.detail.userInfo));
    let info = e.detail.userInfo;
    if (!commonUtil.isEmpty(info)) {
      var params = new Object();
      params.openId = wx.getStorageSync("openidKey");
      params.nick = info.nickName;
      params.sex = info.gender;//性别 1 男，2 女，0未知
      params.img = info.avatarUrl;//头像
      params.country = info.country;
      params.provice = info.province;
      params.city = info.city;
      // params.unionId = this.data.unionId;
      params.agentCode = globalData.agentCode;//代理商编码，小程序固定值
      params.parentCode = wx.getStorageSync("parentCode");//推荐用户编码
      //params.businessCode = wx.getStorageSync("businessCode");//商家编码
      console.log("注册params:" + JSON.stringify(params));
      commonUtil.showLoading("请稍等...");
      wx.request({
        // header: {"content-Type": "application/x-www-form-urlencoded" },
        url: httpsUrl + "/regist?parentCode=" + params.parentCode,
        dataType: "json",
        method: "POST",
        data: params,
        success: function (result) {
          commonUtil.hideLoading();
          var res = result.data;
          console.log("注册返回：" + JSON.stringify(res));
          if (res.result == 0) {
            commonUtil.showSuccessToast("注册成功");
            that.setData({ registerFlag: 0 })
            that.searchUser();
          } else {
            commonUtil.showModal("注册失败！" + res.message);
          }
        }
      })
    }
  },
  //手机号授权获取
  getphonenumber: function (e) {
    this.setData({ phoneFlag: 0 })
    //console.log("encryptedData:" + JSON.stringify(e.detail.encryptedData));
    if (commonUtil.isEmpty(e.detail.encryptedData)) {
      return;
    }
    let that = this;
    var params = new Object();
    params.encryptedData = e.detail.encryptedData;
    params.iv = e.detail.iv;
    // params.code = wx.getStorageSync("code");
    params.sessionKey = wx.getStorageSync("sessionKey");
    console.log("手机解密参数：" + JSON.stringify(params));
    wx.request({
      header: { "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/wechat/xcxUserPhone",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (result) {
        var res = result.data;
        console.log("解密结果：" + JSON.stringify(res));
        if (res.result == 0) {
          let data = JSON.parse(res.data);
          let phone = data.phoneNumber;
          console.log(phone);
          commonUtil.updatePhoneByWechat(phone);
        }
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  }

})